package com.fuhe.chen.vendingmachine.aspect;

import com.fuhe.chen.vendingmachine.anno.AddLog;
import com.fuhe.chen.vendingmachine.pojo.Log;
import com.fuhe.chen.vendingmachine.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Aspect
@Service("AddLogAspect")
public class AddLogAspect {

    @Autowired
    ILogService logService;

    @Pointcut("@annotation(com.fuhe.chen.vendingmachine.anno.AddLog)")
    public void annotationPointCut(){}

    //记录日志
    @After("annotationPointCut()")
    public void doAfter(JoinPoint joinPoint) throws Throwable{
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 反射获取目标类
        Class<?> targetClass = joinPoint.getTarget().getClass();
        // 拿到方法对应的参数类型
        Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        // 根据类、方法、参数类型（重载）获取到方法的具体信息
        Method objMethod = targetClass.getMethod(methodName, parameterTypes);
        // 拿到方法定义的注解信息
        AddLog annotation = objMethod.getAnnotation(AddLog.class);
        String operation = annotation.operation();
        logService.addLog(Log.logging(operation));
    }
}
